-- iterator factory (a closure)
function values (t)
	local i = 0
	return function () i = i + 1; return t[i] end
end

t = {10, 20, 30}

local iter = values(t) 		-- create a iterator
print("call iterator: ")
while true do
	local element = iter() 	-- call the iterator
	if element == nil then break end
	print(element)
end

print("for loop: ") 			-- call the iterator in each loop
													-- keep the iterator's state
for element in values(t) do
	print(element)
end

function allwords () 			-- a iterator that traverses all words from stdin
	local line = io.read() 	-- current line
	local pos = 1 					-- current line's current location
	return function ()
		while line do
			local w, e = string.match(line, "(%w+)()", pos)
			if w then 					-- find a word
				pos = e 					-- next find position
				return w
			else
				line = io.read() 	-- not find a word, try the next line
				pos = 1 					-- find from start
			end
		end
		return nil 						-- no lines left, end the iterations
	end
end

for w in allwords() do
	print(w)
end
